package com.hebxy.ssm.controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.MonthDay;
import java.time.Year;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hebxy.ssm.entity.Plan;
import com.hebxy.ssm.entity.RechargeRecord;
import com.hebxy.ssm.entity.User;
import com.hebxy.ssm.entity.Zfpassword;
import com.hebxy.ssm.entity.Bill;
import com.hebxy.ssm.entity.ChangJing;
import com.hebxy.ssm.entity.Consumption_record;
import com.hebxy.ssm.entity.jy1;
import com.hebxy.ssm.service.PlanService;
import com.hebxy.ssm.service.RechargeRecordService;
import com.hebxy.ssm.service.UserService;
import com.hebxy.ssm.service.ZfpasswordService;

import com.hebxy.ssm.service.BillService;
import com.hebxy.ssm.service.ConsumptionService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	
	@Autowired
	private PlanService planService;
	
	@Autowired
	private ZfpasswordService zfpasswordservice;
	
	@Autowired
	private RechargeRecordService rechargeRecordService;
	
	@Autowired
	private BillService billService;
	
	@Autowired
	private ConsumptionService consumptionService;
	
	@RequestMapping("/getBillById")
	public String getbillById(HttpServletRequest request,ModelMap m){
		
		String card=(String) request.getSession().getAttribute("username");
		User user=userService.findByCardNumber(card);
		Plan plan=planService.findPlanById(user.getPlan_id());
		Bill bill0 = billService.findBillById(user.getId());
		if(bill0==null){
			Bill bi=new Bill();
			bi.setUser_id(user.getId());
			bi.setPackage_fee(plan.getMonthly_fee());
			double a=0,b=0,c=0;
			List<Consumption_record> consumption=consumptionService.findConsumptionById(user.getId());
			for(Object o:consumption){
			    Consumption_record record = (Consumption_record)o;
			    if((record.getType()).equals("上网")){
			    	a=(record.getOver_usage())*(plan.getOver_data_rate());
			    }else if((record.getType()).equals("通话")){
			    	b=(record.getOver_usage())*(plan.getOver_call_rate());
			    }else{
			    	c=(record.getOver_usage())*(plan.getOver_sms_rate());
			    }
			}
			bi.setOver_fee(a+b+c);
			bi.setTotal_amount(bi.getPackage_fee()+bi.getOver_fee());
			bi.setMonth(Year.now() + "-" + MonthDay.now().getMonthValue());
			billService.addBill(bi);
		}
		
				
		Bill bill = billService.findBillById(user.getId());
		bill.setTotal_amount(bill.getOver_fee()+bill.getPackage_fee());
		
		
		m.put("card", card);
		m.put("bill", bill);
		
		return "user/userBill";
		
	}
	
	@RequestMapping("/getPlanById")
	public String getPlanById(HttpServletRequest request,ModelMap m){
		String card=(String) request.getSession().getAttribute("username");
		User user=userService.findByCardNumber(card);
		Plan plan=planService.findPlanById(user.getPlan_id());
		List<Consumption_record> consumption=consumptionService.findConsumptionById(user.getId());
		Integer flag1=0,flag2=0,flag3=0;
		if(consumption.isEmpty()){
			Integer RemData=plan.getData_usage();
			Integer RemMin=plan.getCall_time();
			Integer RemMes=plan.getSms_count();
			
			m.put("RemData", RemData);
			m.put("RemMin", RemMin);
			m.put("RemMes", RemMes);
		}else if(consumption != null && !consumption.isEmpty()){
			for(Object o:consumption){
				Consumption_record record = (Consumption_record)o;
				if(record.getType().equals("上网")){
					flag1=1;
				}
			}
			if(flag1==0){
				m.put("RemData", plan.getData_usage());
			}else{
				for(Object o:consumption){
					Consumption_record record = (Consumption_record)o;
					if((record.getType()).equals("上网")){
				    	if(plan.getData_usage()-record.getUsage_amount()>0){
				    		Integer RemData=plan.getData_usage()-record.getUsage_amount();
				    		m.put("RemData", RemData);
				    	}else{
				    		Integer RemData=0;
				    		m.put("RemData", RemData);
				    	}
				    }
				}
			}
			for(Object o:consumption){
				Consumption_record record = (Consumption_record)o;
				if(record.getType().equals("通话")){
					flag2=1;
				}
			}
			if(flag2==0){
				m.put("RemMin", plan.getCall_time());
			}else{
				for(Object o:consumption){
					Consumption_record record = (Consumption_record)o;
					if((record.getType()).equals("通话")){
				    	if(plan.getCall_time()-record.getUsage_amount()>0){
				    		Integer RemMin=plan.getCall_time()-record.getUsage_amount();
					    	m.put("RemMin", RemMin);
				    	}else{
				    		Integer RemMin=0;
				    		m.put("RemMin", RemMin);
				    	}
				    }
				}
			}
			for(Object o:consumption){
				Consumption_record record = (Consumption_record)o;
				if(record.getType().equals("短信")){
					flag3=1;
				}
			}
			if(flag3==0){
				m.put("RemMes", plan.getSms_count());
			}else{
				for(Object o:consumption){
					Consumption_record record = (Consumption_record)o;
					if((record.getType()).equals("短信")){
						if(plan.getSms_count()-record.getUsage_amount()>0){
				    		Integer RemMes=plan.getSms_count()-record.getUsage_amount();
					    	m.put("RemMes", RemMes);
				    	}else{
				    		Integer RemMes=0;
				    		m.put("RemMes", RemMes);
				    	}
					}
				}
			}
		}
		
		m.put("plan", plan);
		
		return "user/userPlan";
	}
	
	@RequestMapping("/index")
	public String index(){
		return "user/index";
	}
	@RequestMapping("/login")
	public String Tologin(HttpServletRequest request){
		String str=(String) request.getSession().getAttribute("username");
		if(str!=null){
			return "main";
		}
		return "forward:/login.jsp";
		
	}
	@RequestMapping("/userLogin")
	public String login(@ModelAttribute("user") @Validated(value=jy1.class) User user,BindingResult r,HttpServletRequest request,ModelMap m){
		HttpSession session=request.getSession();
		if(r.hasErrors()){
			List<ObjectError> errors=r.getAllErrors();
			for(ObjectError o:errors){
				System.out.println(o.getDefaultMessage());
			}
			m.put("error", errors);
			return "forward:/login.jsp";
		}
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("card_number", user.getCard_number());
		map.put("password", user.getPassword());
		User user1=userService.findForlogin(map);
		if(user1!=null){
			String originalUrl =(String) session.getAttribute("originalUrl");
			
			session.setAttribute("username", user.getCard_number());
			System.out.println(originalUrl);
			if((originalUrl!=null&&!originalUrl.isEmpty())&&!originalUrl.equals("/login")&&!originalUrl.equals("/role**")){
				return "redirect:"+originalUrl;
			}
			return "main";
		}
		else{
			m.addAttribute("msg","卡号或者密码错误 请重新输入");
			return "forward:/login.jsp";
		}
		
	}
	@RequestMapping("/{page}")
	public String gotoAddUser(@PathVariable("page") String page,HttpServletRequest request){
		return "user/"+page;
	}
	
	@GetMapping("/userRegister")
	public String userRegister(ModelMap m){
		kaHaoHeTaoCan(m);
		return "/user/userRegister";
	}
	
	@PostMapping("/register")
	public String register(@ModelAttribute("user") @Validated User user,BindingResult r,ModelMap m){
		if(r.hasErrors()){
			List<ObjectError> errors = r.getAllErrors();
			for(ObjectError error:errors){
				System.out.println(error.getDefaultMessage());
			}
			m.put("msg", "校验不合格 注册用户失败");
			m.put("errors", errors);
			kaHaoHeTaoCan(m);
			return "user/userRegister";
		}
		Plan plan=planService.findPlanById(user.getPlan_id());
		if(user.getPrepaid_amount()<plan.getMonthly_fee()){
			m.put("msg2", "您预存的话费金额不足以支付本月固定套餐资费，请重新充值！");
			kaHaoHeTaoCan(m);
			return "user/userRegister";
		}
		user.setBalance(user.getPrepaid_amount()-plan.getMonthly_fee());
		userService.addUser(user);
		m.put("msg1", "注册成功，可以点击此处前往登录页面");
		m.put("card_number", user.getCard_number());
		m.put("taocan", planService.findPlanById(user.getPlan_id()));
		return "/user/userRegister";
		
	}
	//生成卡号
	public void kaHaoHeTaoCan(ModelMap m){
	List<String> card_numbers =new ArrayList<>();
	for(int i=0;i<10;i++){
		String numb="139";
		for(int j=0;j<8;j++){
			numb=numb+new Random().nextInt(10);
		}
		User user=userService.findByCardNumber(numb);
		if(user!=null){
			i=i-1;
		}else{
			System.out.println(numb);
			card_numbers.add(numb);
		}
	}
	m.addAttribute("card_numbers", card_numbers);
	
	List<Plan> plans= planService.findPlanAll();
	m.addAttribute("plans",plans );
	}
	
	
    @GetMapping("/userCancel")
    public String userCancel(Model model, HttpServletRequest request) {
        // 从会话中获取当前登录的用户信息
        String usercard= (String) request.getSession().getAttribute("username");
        if (usercard != null) {
            model.addAttribute("cardNumber", usercard);
        }
        return "/user/userCancel";
    }

    @PostMapping("/cancel")
    public String userCancel(RedirectAttributes redirectAttributes, HttpServletRequest request) {
    	String usercard= (String) request.getSession().getAttribute("username");
        User user = userService.findByCardNumber(usercard);
        if (user != null) {
        	System.out.println(user);
            user.setStatus(0);
            userService.updateUser(user);
            request.getSession().removeAttribute("username");
            redirectAttributes.addFlashAttribute("msg", "卡号已注销，您已退出登录");
            return "redirect:/user/userLogin";
        } else {
            redirectAttributes.addFlashAttribute("msg", "卡号不存在");
            return "redirect:/user/userCancel";
        }
    }
    @GetMapping("/userUpdatePlan")
    public String showUpdatePlanPage(Model model, HttpServletRequest request) {
        // 从会话中获取当前登录的用户信息
        String usercard = (String) request.getSession().getAttribute("username");
        if (usercard != null) {
            model.addAttribute("cardNumber", usercard);
            // 可以添加当前计划信息到模型
            User user = userService.findByCardNumber(usercard);
            model.addAttribute("currentPlan", user.getPlan_id());
        }
        return "/user/userUpdatePlan"; // 返回更新计划的视图页面
    }
    @PostMapping("/updatePlan")
    public String updateUserPlan(@RequestParam("plan_id") Integer plan_id,
                               ModelMap m,
                               HttpServletRequest request) {
        String usercard = (String) request.getSession().getAttribute("username");

        try {
        	User user=userService.findByCardNumber(usercard);
        	user.setPlan_id(plan_id);
            userService.updateUser(user);
            m.put("msg", "套餐更新成功");
            return "redirect:/user/userUpdatePlan";
        } catch (Exception e) {
        	m.put("msg", "套餐更新失败");
            return "redirect:/user/userUpdatePlan";
        }
    }
    @GetMapping("/huafeicz")
	public String huafeicz(HttpServletRequest request,Model m){
		String cardnumber = (String)request.getSession().getAttribute("username");
		m.addAttribute("card_numb", cardnumber);
		return "user/huafeicz";
	}
    //新加入的
   	@PostMapping("/recharge")
   	@ResponseBody
   	public ModelMap recharge(HttpServletRequest request,HttpServletResponse response,ModelMap m,@RequestParam double amount) throws Exception{
   		String phone=request.getParameter("phone");
   		String paymentType = request.getParameter("paymentType");
   	    String password = request.getParameter("password");
   	    String card=(String) request.getSession().getAttribute("username");
   	    User user=userService.findByCardNumber(phone);
   	    
   	    //验证手机号
   	    if(!phone.matches("^139\\d{8}$") || user.getStatus()==0){
   	    	m.put("success", false);
   	    	m.put("message", "手机号格式错误,或者卡号被注销");
   	    	sendJsonResponse(response,m);
   	    	return m;
   	    }
   	    User user2=userService.findByCardNumber(card);
   	    Zfpassword zfmm=zfpasswordservice.findzfmmById(user2.getId());
   	    RechargeRecord r=new RechargeRecord();
   	    r.setUser_id(user.getId());
   	    r.setAmount(amount);
   	    //验证密码
   	    if("wx".equals(paymentType)){
   	    	if(password.equals(zfmm.getWxpassword())){
   	    		user.setBalance(amount+user.getBalance());
   	    		userService.updateUser(user);
   	    		m.put("success", true);
   	    		sendJsonResponse(response,m);
   	    		r.setPayment_method("微信");
   	    		rechargeRecordService.addczjl(r);
   	    		return m;
   	    	}else{
   	    		m.put("success", false);
   	    		m.put("message", "充值密码错误请重新输入");
   	    		sendJsonResponse(response,m);
   	    		return m;
   	    	}
   	    }
   	    if("zfb".equals(paymentType)){
   	    	if(password.equals(zfmm.getZfbpassword())){
   	    		user.setBalance(amount+user.getBalance());
   	    		userService.updateUser(user);
   	    		m.put("success", true);
   	    		sendJsonResponse(response,m);
   	    		r.setPayment_method("支付宝");
   	    		rechargeRecordService.addczjl(r);
   	    		return m;
   	    	}else{
   	    		m.put("success", false);
   	    		m.put("message", "充值密码错误请重新输入");
   	    		sendJsonResponse(response,m);
   	    		return m;
   	    	}
   	    }
   		return m;	
   	}
   	
   	private void sendJsonResponse(HttpServletResponse response,ModelMap m) throws Exception{
   		response.setContentType("application/json");
   		response.setCharacterEncoding("UTF-8");
   		new ObjectMapper().writeValue(response.getWriter(),m);
   	}
	
   	
  //使用哈移动
   	@RequestMapping("/useHaYiDong")
   	public String useHaYiDong(HttpServletRequest request,ModelMap m){
   		List<ChangJing> cjList = GetChangJing();
   		Random ran=new Random();
   		String card=(String) request.getSession().getAttribute("username");
   		User user=userService.findByCardNumber(card);
   		Plan plan=planService.findPlanById(user.getPlan_id());
   		int usage_amount=0,package_usage=0,over_usage=0;
   		int th_amount=0,package_th=0,over_th=0;
   		int dx_amount=0,package_dx=0,over_dx=0;
   		int ll_amount=0,package_ll=0,over_ll=0;
   		List<Consumption_record> xfjlList=consumptionService.findConsumptionById(user.getId());
   		if(xfjlList!=null){
   			for(Consumption_record c:xfjlList){
   				if("通话".equals(c.getType())){
   					th_amount+=c.getUsage_amount();
   					package_th+=c.getPackage_usage();
   					over_th+=c.getOver_usage();
   				}
   				if("短信".equals(c.getType())){
   					dx_amount+=c.getUsage_amount();
   					package_dx+=c.getPackage_usage();
   					over_dx+=c.getOver_usage();
   				}
   				if("上网".equals(c.getType())){
   					ll_amount+=c.getUsage_amount();
   					package_ll+=c.getPackage_usage();
   					over_ll+=c.getOver_usage();
   				}
   			}
   		}
   		for(int i=0;i<cjList.size();i++){
   			if(user.getPlan_id()==1){
   				ChangJing cj=cjList.get(ran.nextInt(cjList.size()));
   				if(cj.getType().equals("通话")){
   					Consumption_record cons=new Consumption_record();
   					cons.setUser_id(user.getId());
   					cons.setType(cj.getType());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=th_amount+cj.getXf();
   					if(amount>=plan.getCall_time()){
   						cons.setPackage_usage(plan.getCall_time());
   						if(th_amount<plan.getCall_time()){
   							cons.setOver_usage(amount-plan.getCall_time());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_call_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","通话时长为"+cj.getXf()+"分钟");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   				}else if(cj.getType().equals("短信")){
   					Consumption_record cons=new Consumption_record();
   					cons.setUser_id(user.getId());
   					cons.setType(cj.getType());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=dx_amount+cj.getXf();
   					if(amount>=plan.getSms_count()){
   						cons.setPackage_usage(plan.getSms_count());
   						if(dx_amount<plan.getSms_count()){
   							cons.setOver_usage(amount-plan.getSms_count());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_sms_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","短信条数为"+cj.getXf()+"条");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   				}
   			}
   			else if(user.getPlan_id()==2){
   				ChangJing cj=cjList.get(ran.nextInt(cjList.size()));
   				if(cj.getType().equals("上网")){
   					Consumption_record cons=new Consumption_record();
   					cons.setUser_id(user.getId());
   					cons.setType(cj.getType());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=ll_amount+cj.getXf();
   					if(amount>=plan.getData_usage()){
   						cons.setPackage_usage(plan.getData_usage());
   						if(ll_amount<plan.getData_usage()){
   							cons.setOver_usage(amount-plan.getData_usage());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_data_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","上网使用流量为"+cj.getXf()+"MB");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   				}
   			}
   			else{
   				ChangJing cj=cjList.get(ran.nextInt(cjList.size()));
   				if(cj.getType().equals("通话")){
   					Consumption_record cons=new Consumption_record();
   					cons.setType(cj.getType());
   					cons.setUser_id(user.getId());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=th_amount+cj.getXf();
   					if(amount>=plan.getCall_time()){
   						cons.setPackage_usage(plan.getCall_time());
   						if(th_amount<plan.getCall_time()){
   							cons.setOver_usage(amount-plan.getCall_time());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_call_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","通话时长为"+cj.getXf()+"分钟");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   				}else if(cj.getType().equals("短信")){
   					Consumption_record cons=new Consumption_record();
   					cons.setUser_id(user.getId());
   					cons.setType(cj.getType());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=dx_amount+cj.getXf();
   					if(amount>=plan.getSms_count()){
   						cons.setPackage_usage(plan.getSms_count());
   						if(dx_amount<plan.getSms_count()){
   							cons.setOver_usage(amount-plan.getSms_count());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_sms_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","短信条数为"+cj.getXf()+"条");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   				}else if(cj.getType().equals("上网")){
   					Consumption_record cons=new Consumption_record();
   					cons.setUser_id(user.getId());
   					cons.setType(cj.getType());
   					cons.setUsage_amount(cj.getXf());
   					cons.setScene_description(cj.getChangj());
   					int amount=ll_amount+cj.getXf();
   					if(amount>=plan.getData_usage()){
   						cons.setPackage_usage(plan.getData_usage());
   						if(ll_amount<plan.getData_usage()){
   							cons.setOver_usage(amount-plan.getData_usage());
   						}else{
   							cons.setOver_usage(cj.getXf());
   						}
   						cons.setCost(cons.getOver_usage()*plan.getOver_data_rate());
   					}else{
   						cons.setPackage_usage(amount);
   						cons.setOver_usage(0);
   						cons.setCost(0);
   					}
   					if(user.getBalance()-cons.getCost()>0){
   					m.put("msg", "尊敬的用户，恭喜你成功模拟使用哈移动");
   					m.put("cjxx1","本次模拟使用哈移动类型为:"+cj.getType());
   					m.put("cjxx2","上网使用流量为"+cj.getXf()+"MB");
   					m.put("cjxx3","使用场景为"+cj.getChangj());
   					consumptionService.addConsumptionRecord(cons);
   					user.setBalance(user.getBalance()-cons.getCost());
   					userService.updateUser(user);
   					return "user/HaYiDong";
   					}else{
   						m.put("msg", "尊敬的用户,模拟使用哈移动失败,原因是你的余额已不足支付:"+cons.getCost()+"元");
   						m.put("cz", "点击此处可前往充值");
   						return "user/HaYiDong";
   					}
   			}
   		}
   	}
   		return "user/HaYiDong";
   	}
   	
   	//加入场景
   	public List<ChangJing> GetChangJing(){
   		List<ChangJing> cjList=new ArrayList<>();
   		cjList.add(new ChangJing(1,"通话",90,"问候客户  谁知其如此难缠 通话90分钟"));
   		cjList.add(new ChangJing(2,"通话",30,"询问妈妈身体状况 本地通话 30 分钟"));
   		cjList.add(new ChangJing(3,"短信",5,"参与环境保护实施方案问卷调查 发送短信 5 条"));
   		cjList.add(new ChangJing(4,"短信",50,"通知朋友手机换号 发送短信 50 条"));
   		cjList.add(new ChangJing(5,"上网",1024,"和女友微信视频聊天 使用流量 1G"));
   		cjList.add(new ChangJing(6,"上网",2048,"晚上手机在线看韩剧 不留神睡着啦 使用流量 2G"));
		return cjList;
   		
   	}
   	
   	//资费说明
   	@RequestMapping("/zfsm")
   	public String zfsm(ModelMap m) throws Exception{
   		StringBuilder buil=new StringBuilder();
   		
   	
   		
   		File file = new File(getClass().getClassLoader().getResource("套餐资费说明.txt").getFile());
   		System.out.println("aaaaa"+file);

   		BufferedReader r=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
   		
   		String str=null;
   		while((str=r.readLine())!=null){
   			buil.append("<p>").append(str).append("</p>");
   		}
   		m.put("msg", buil);
   		r.close();
   		return "user/zfsm";
   	}
   	@RequestMapping("userDaYing")
    public String userDaYing(HttpServletRequest request,ModelMap m){
   		String card=(String) request.getSession().getAttribute("username");
   		User user=userService.findByCardNumber(card);
   		List<Consumption_record>xfjls=consumptionService.findConsumptionById(user.getId());
   		if(xfjls!=null){
   			try{
   			File file = new File(getClass().getClassLoader().getResource("").getFile());
   			System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaa"+file);
   			BufferedWriter w=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file+"/"+card+"xfqd.txt"),"UTF-8"));
   			//BufferedWriter w = new BufferedWriter(new FileWriter(file+"/"+card+"xfqd.txt"));
   			w.write("******"+card+"消费记录******");
   			w.newLine();
   			w.write("序号"+"  "+"类型"+"  "+"数据(通话(分钟)/上网(MB)/短信(条))");
   			w.newLine();
   			int i=1;
   			for(Consumption_record xf:xfjls){
   				w.write(i+".   "+xf.getType()+"      "+xf.getUsage_amount());  
   				w.newLine();
   				w.flush();
   				i++;   
   			}
   			w.close();
   			}catch(Exception e){
   				e.printStackTrace();
   			}
    	}
   		else {
			m.put("msg", "对不起，不存在消费记录，不能打印");
		}
		return "user/xfzd";	
   	}

   @RequestMapping("/Download")
   public String Download(HttpServletRequest request,HttpServletResponse response,ModelMap m) throws Exception{
	   String card=(String) request.getSession().getAttribute("username");
	   File file = new File(getClass().getClassLoader().getResource(card+"xfqd.txt").getFile());
	   String fileName=card+"xfqd.txt";
	   response.reset();
	   response.setCharacterEncoding("UTF-8");
	   response.setContentType("multipart/form-data;charset=UTF-8");
	   response.setHeader("Content-Disposition", "attachment;fileName="+URLEncoder.encode(fileName,"utf-8"));
	   BufferedReader r=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
	   BufferedWriter w=new BufferedWriter(new OutputStreamWriter(response.getOutputStream(),"UTF-8"));
	   String str=null;
	   while((str=r.readLine())!=null){
		   w.write(str);
		   w.newLine();
	   }
	   	r.close();
		w.close();
		return "user/xfzd";
	}

}
    
   

